# src/crud/sys_objects.py
from typing import List, Optional
from sqlalchemy.orm import Session
from src.models import sys_objects as models
from src.schemas import sys_objects as schemas
from src.schemas import request_model
from src.core import orm_curd
from src.schemas.login_manager import AuthManager


# ---------------------- 单条新增 ----------------------
def create_object(db: Session,
                  auth: AuthManager,
                  obj: schemas.SysObjectsCreate) -> dict:
    return orm_curd.Insert(
        db,
        auth,
        models.SysObjects,
        schemas.SysObjects,
        "系统对象",
        [obj.dict()],
        ["api_id", "object_name"],
        skip_duplicates=True
    )


# ---------------------- 批量新增 ----------------------
def create_objects(db: Session,
                   auth: AuthManager,
                   objs: List[schemas.SysObjectsCreate]) -> dict:
    return orm_curd.Insert(
        db,
        auth,
        models.SysObjects,
        schemas.SysObjects,
        "系统对象",
        objs,
        ["api_id", "object_name"],
        skip_duplicates=True
    )


# ---------------------- 分页查询 ----------------------
def get_objects(db: Session,
                auth: AuthManager,
                page: int = 1,
                page_size: int = 100,
                filter_model: Optional[request_model.QueryModel] = None,
                id: Optional[str] = None) -> dict:
    return orm_curd.query_with_page(
        db,
        auth,
        models.SysObjects,
        schemas.SysObjects,
        id=id,
        filter_model=filter_model,
        page=page,
        page_size=page_size
    )


# ---------------------- 单条更新 ----------------------
def update_object(db: Session,
                  auth: AuthManager,
                  obj_id: str,
                  obj: schemas.SysObjects) -> schemas.SysObjects:
    update_model = request_model.UpdateModel([
        request_model.UpdateItem(
            pk_names=["id"],
            pk_values=[obj_id],
            data=obj.dict(exclude_unset=True)
        )
    ])
    return orm_curd.update(db, auth, models.SysObjects, update_model)


# ---------------------- 批量更新 ----------------------
def update_objects(db: Session,
                   auth: AuthManager,
                   update_model: request_model.UpdateModel) -> dict:
    return orm_curd.update(db, auth, models.SysObjects, update_model)


# ---------------------- 删除 ----------------------
def delete_objects(db: Session,
                   auth: AuthManager,
                   delete_model: request_model.DeleteModel) -> dict:
    return orm_curd.delete(
        db=db,
        auth=auth,
        model_cls=models.SysObjects,
        delete_obj=delete_model
    )
